/*
 * Copyright (C) 2018 Logos Technology Ltd.
 */

package com.logos.tool;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.location.LocationManager;
import android.os.Build;
import android.util.TypedValue;
import android.view.View;
import android.widget.LinearLayout;

import com.google.android.material.tabs.TabLayout;
import com.logos.tool.log.LogUtil;
import com.logos.tool.string.StringUtil;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import static android.content.ContentValues.TAG;
import static android.content.Context.CLIPBOARD_SERVICE;

public class PhoneUtils {

    private static List<byte[]> sMemoryExhauster;

    public static boolean isGpsEquipped() {
        return ApplicationUtil.getContext().getPackageManager()
                .hasSystemFeature(PackageManager.FEATURE_LOCATION_GPS);
    }

    /**
     * @return true 为GPS可用,false为GPS不可用.
     */
    public static boolean isGpsEnabled() {
        try {
            LocationManager locationManager = (LocationManager) ApplicationUtil.getContext()
                    .getSystemService(Context.LOCATION_SERVICE);
            return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        } catch (SecurityException e) {
            return false;
        }

    }

    /**
     * Allocate and hold memory till memory exhausted.
     */
    public static synchronized void simulateExhaustMemory() {
        if (null == sMemoryExhauster) {
            sMemoryExhauster = new ArrayList<>();
        }

        final int initialByteArraySize = 32 * 1024 * 1024; // 32MB
        byte[] ba;
        int byteArraySize;
        long totalBytesConsumed = 0;

        do {
            ba = null;
            byteArraySize = initialByteArraySize;
            do {
                try {
                    ba = new byte[byteArraySize];
                    sMemoryExhauster.add(ba);
                    LogUtil.verbose(TAG, "exhaustMemory ba[" + ba.length + "]");

                    totalBytesConsumed += byteArraySize;
                    LogUtil.verbose(TAG, "exhaustMemory totalBytesConsumed "
                            + (totalBytesConsumed / 1024) + " KB");
                } catch (OutOfMemoryError e) {
                    byteArraySize /= 2;
                }
            } while (null == ba && byteArraySize > 2);
        } while (ba != null);
    }

    /**
     * Release memory allocated and hold by {@link PhoneUtils#simulateExhaustMemory()}.
     */
    public static synchronized void releaseSimulateExhaustMemory() {
        if (null == sMemoryExhauster) {
            return;
        }

        sMemoryExhauster.clear();
        sMemoryExhauster = null;
    }

    /**
     * 获取状态栏高度
     *
     * @param context 上下文.
     * @return 返回高度大小.
     */
    public static int getStatusBarHeight(Context context) {
        Class<?> classObj;
        Object obj;
        Field field;
        int statusBarHeight = 0;
        try {
            classObj = Class.forName("com.android.internal.R$dimen");
            obj = classObj.newInstance();
            field = classObj.getField("status_bar_height");
            statusBarHeight = context
                    .getResources().getDimensionPixelSize(
                            Integer.parseInt(field.get(obj).toString()));
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return statusBarHeight;
    }

    /**
     * set table layout
     *
     * @param tabs     tab
     * @param leftDip  dip
     * @param rightDip dip
     */
    public static void setTableLayoutIndicator(TabLayout tabs, int leftDip, int rightDip) {
        try {
            Class<?> tabLayout = tabs.getClass();
            Field tabStrip = null;
            try {
                tabStrip = tabLayout.getDeclaredField("slidingTabIndicator");
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
            tabStrip.setAccessible(true);
            LinearLayout llTab = null;
            try {
                llTab = (LinearLayout) tabStrip.get(tabs);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }

            int left = (int) TypedValue.applyDimension(
                    TypedValue.COMPLEX_UNIT_DIP, leftDip,
                    Resources.getSystem().getDisplayMetrics());
            int right = (int) TypedValue.applyDimension(
                    TypedValue.COMPLEX_UNIT_DIP, rightDip,
                    Resources.getSystem().getDisplayMetrics());

            for (int i = 0; i < llTab.getChildCount(); i++) {
                View child = llTab.getChildAt(i);
                child.setPadding(0, 0, 0, 0);
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0,
                        LinearLayout.LayoutParams.MATCH_PARENT, 1);
                params.leftMargin = left;
                params.rightMargin = right;
                child.setLayoutParams(params);
                child.invalidate();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * get drawable
     *
     * @param context context
     * @param id      id
     * @return drawable
     */
    public static Drawable getDrawable(Context context, int id) {
        Resources resources = context.getResources();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            return resources.getDrawable(id, context.getTheme());
        } else {
            return resources.getDrawable(id);
        }
    }

    /**
     * 根据开始字符串和结束字符串，返回它们中间的字符
     *
     * @param context context
     * @param start   开始字符
     * @param end     结束字符
     * @return 返回中间的字符
     */
    public static String getTextFormClipboardByString(Context context, String start, String end) {
        String result = "";
        ClipboardManager cm = (ClipboardManager) context.getSystemService(CLIPBOARD_SERVICE);
        ClipData data = cm.getPrimaryClip();
        if (data == null) {
            return result;
        }
        ClipData.Item item = data.getItemAt(0);
        if (item == null || item.getText() == null) {
            return result;
        }
        String content = item.getText().toString();
        if (StringUtil.isEmpty(content)) {
            return result;
        }

        if (content.contains(start) && content.contains(end)) {
            String[] strings = content.split(start);
            String startString = strings[1];
            if (!startString.contains(end)) {
                return result;
            }
            result = startString.split(end)[0];
            return result;
        } else {
            return result;
        }
    }
}
